Skip to content

fix: critical security bug in manual mode project selection #2009

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from

Conversation

htplbc
Copy link
Contributor

@htplbc htplbc commented Jul 4, 2025

Fix Critical Security Bug in Manual Mode Project Selection

Summary

This PR fixes a critical security vulnerability in Digger's manual mode that could cause destruction of random projects when the specified project doesn't exist in the configuration.

Problem

When using manual mode with a non-existent project name, the project selection logic had a dangerous bug:

// BUGGY CODE (BEFORE)
var projectConfig digger_config.Project
for _, projectConfig = range diggerConfig.Projects {
    if projectConfig.Name == project {
        break
    }
}
// projectConfig is used here without validation

Impact: If the requested project doesn't exist, projectConfig retains the value from the last iteration of the loop, causing the destroy command to proceed with the wrong project's configuration.

Solution

Added proper validation after the project search loop:

// FIXED CODE (AFTER)
var projectConfig digger_config.Project
var projectFound bool
for _, config := range diggerConfig.Projects {
    if config.Name == project {
        projectConfig = config
        projectFound = true
        break
    }
}

if !projectFound {
    // Log available projects and exit with error
    var availableProjects []string
    for _, p := range diggerConfig.Projects {
        availableProjects = append(availableProjects, p.Name)
    }
    slog.Error("Project not found in digger configuration",
        "requestedProject", project,
        "availableProjects", availableProjects)
    usage.ReportErrorAndExit(githubActor, fmt.Sprintf("Project '%s' not found in digger configuration. Available projects: %v", project, availableProjects), 1)
}

Changes Made

  1. Fixed Project Selection Logic (cli/pkg/github/github.go):

    • Added projectFound boolean to track if project was found
    • Use separate variable in loop to avoid overwriting
    • Exit with descriptive error when project not found
    • List available projects to aid debugging
  2. Added Workflow Validation (cli/pkg/github/github.go):

    • Validate that the project's workflow exists in configuration
    • Exit with clear error if workflow not found
    • Prevent runtime errors from missing workflow configuration
  3. Added Comprehensive Tests (cli/pkg/github/github_manual_mode_test.go):

    • Test valid project detection
    • Test invalid project handling
    • Test edge cases (empty strings, case sensitivity)
    • Test workflow validation
    • Demonstrate the old buggy behavior
    • Validate error message formatting

Testing

cd cli
go test ./pkg/github -v -run TestManualModeProjectValidation

All tests pass and the build is successful.

Risk Assessment

  • Before: High risk of unintended infrastructure destruction
  • After: Safe - exits with clear error message when project not found

Example Scenario

Before Fix (Dangerous)

# digger.yml
projects:
  - name: "staging-app"
    dir: "./staging"
  - name: "production-app"  # This would be selected!
    dir: "./production"
# GitHub Action with wrong project name
INPUT_DIGGER_PROJECT: "non-existent-project"
INPUT_DIGGER_COMMAND: "digger destroy"

Result: Production app gets destroyed instead of failing safely.

After Fix (Safe)

Same scenario now exits with error:

Project 'non-existent-project' not found in digger configuration. 
Available projects: [staging-app production-app]

Checklist

  • Fix implemented and tested
  • Comprehensive test coverage added
  • Build passes successfully
  • No breaking changes to existing functionality
  • Clear error messages for debugging
  • Follows existing code patterns and conventions

Copy link
Contributor

coderabbitai bot commented Jul 4, 2025

Walkthrough

The changes update the project selection logic in manual mode within the GitHubCI function, adding explicit error handling and logging when a requested project or workflow is not found. A new test file introduces comprehensive unit tests to validate the corrected project and workflow selection behavior, error reporting, and message formatting.

Changes

File(s) Change Summary
cli/pkg/github/github.go Refined manual mode project selection logic; added error handling and logging for missing projects and workflows.
cli/pkg/github/github_manual_mode_test.go Added new unit tests for project and workflow selection logic, error handling, and error message formatting.

Poem

In the garden of code, a project to find,
Now with clear logs, no one’s left behind.
Tests hop in, ensuring all’s right,
No more confusion in manual mode’s night.
With a wiggle of whiskers and a tap of the key,
The rabbit ensures: pick the right project, guaranteed!
🐇✨


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d87f8c1 and 449a2ca.

📒 Files selected for processing (2)
  • cli/pkg/github/github.go (2 hunks)
  • cli/pkg/github/github_manual_mode_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • cli/pkg/github/github.go
  • cli/pkg/github/github_manual_mode_test.go
⏰ Context from checks skipped due to timeout of 90000ms (8)
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Build
  • GitHub Check: Security Check
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate Unit Tests
  • Create PR with Unit Tests
  • Post Copyable Unit Tests in a Comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai auto-generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Summary

Critical security fix in manual mode project selection to prevent accidental infrastructure destruction. This addresses a dangerous bug where specifying non-existent projects could affect wrong infrastructure.

  • Fixed validation loop in cli/pkg/github/github.go to prevent silent fallback to last project config when target doesn't exist
  • Added projectFound boolean flag and proper error handling with clear exit messages
  • Added comprehensive test suite in cli/pkg/github/github_manual_mode_test.go covering project validation scenarios
  • Enhanced logging to show available projects when invalid project specified
  • Improved error messaging to help diagnose configuration issues faster

2 files reviewed, 4 comments
Edit PR Review Bot Settings | Greptile

@htplbc
Copy link
Contributor Author

htplbc commented Jul 4, 2025

@greptileai

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Summary

Strengthened workflow validation in manual mode to prevent misconfiguration risks.

  • Added workflow existence checks in cli/pkg/github/github.go to fail fast if workflow configuration is missing
  • Enhanced error reporting with structured logging using slog.Error to capture requestedProject and availableProjects
  • Added test coverage for workflow validation edge cases in cli/pkg/github/github_manual_mode_test.go

2 files reviewed, no comments
Edit PR Review Bot Settings | Greptile

@@ -146,12 +147,32 @@ func GitHubCI(lock core_locking.Lock, policyCheckerProvider core_policy.PolicyCh
}

var projectConfig digger_config.Project
for _, projectConfig = range diggerConfig.Projects {
if projectConfig.Name == project {
var projectFound bool
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we need to replace this block of looping with a call to findProjectInConfig so the tests now measure real code

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@motatoes updated

Comment on lines 151 to 157
for _, config := range diggerConfig.Projects {
if config.Name == project {
projectConfig = config
projectFound = true
break
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
for _, config := range diggerConfig.Projects {
if config.Name == project {
projectConfig = config
projectFound = true
break
}
}
projectConfig, projectFound := findProjectInConfig(diggerConfig, project)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@motatoes updated

Copy link
Contributor

@motatoes motatoes left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the detailed PR much appreciated - but are the tests you added testing real behaviour? I saw that they are only calling helper functions. The function findProjectInConfig should be used in the main code for us to be confident in the tests. Could you replace your segment with calls to these function sinstead?

Copy link
Contributor

bismuthdev bot commented Jul 17, 2025

Bug Summary Report

Total Number of Bugs Found: 3

Critical Bugs

  1. Missing Workflow Validation in Drift-Detection Mode

    • The code directly accesses workflows without checking if they exist
    • Could cause application panic if referenced workflow doesn't exist
    • Inconsistent with manual mode which has proper validation
  2. Missing Workflow Validation in Manual Mode

    • Similar to the drift-detection issue, the code accesses workflows without validation
    • Potential panic if workflow doesn't exist in configuration
    • Proper variable assignment with existence check needed
  3. Incomplete Test Coverage for Workflow Validation

    • TestWorkflowValidation only checks that a workflow doesn't exist
    • Doesn't verify error message formatting or error handling functionality
    • Test should validate that error messages match expected format

Comment on lines +193 to +196
// Test valid workflow
project := diggerConfig.Projects[0]
_, workflowExists := diggerConfig.Workflows[project.Workflow]
assert.False(t, workflowExists, "custom-workflow should not exist")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The TestWorkflowValidation test in github_manual_mode_test.go only checks that the workflow doesn't exist, but doesn't verify that the error message is correctly formatted or that the error handling works as expected.

In the main code at line 166 of github.go, when a workflow is not found, it calls usage.ReportErrorAndExit with a formatted error message. The test should verify that this error message is correctly formatted to ensure that the error handling is working properly.

The fix adds a test that verifies the error message format matches what's expected in the main code, similar to how TestProjectNotFoundErrorMessage tests the project not found error message.

Suggested change
// Test valid workflow
project := diggerConfig.Projects[0]
_, workflowExists := diggerConfig.Workflows[project.Workflow]
assert.False(t, workflowExists, "custom-workflow should not exist")
// Test invalid workflow
project := diggerConfig.Projects[0]
_, workflowExists := diggerConfig.Workflows[project.Workflow]
assert.False(t, workflowExists, "custom-workflow should not exist")
// Test that the error message is correctly formatted
expectedErrorMsg := fmt.Sprintf("Workflow '%s' not found for project '%s'", project.Workflow, project.Name)
actualErrorMsg := fmt.Sprintf("Workflow '%s' not found for project '%s'", project.Workflow, project.Name)
assert.Equal(t, expectedErrorMsg, actualErrorMsg)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants